package com.ddh.bankmanager.config;

import com.ddh.bankmanager.enum_.ResultCode;
import com.ddh.bankmanager.exception.ServiceException;
import com.ddh.bankmanager.utils.JwtUtils;
import com.ddh.bankmanager.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * @author young
 * @date 2022/9/12 15:37
 * @description: 获取token并验证
 */
@Component
@Slf4j
public class MyJwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (token == null){
            throw new ServiceException(ResultCode.UNAUTHORIZED);
        }
        if (JwtUtils.parseJWT(token).get("customerId")==null){
            throw new ServiceException(ResultCode.UNAUTHORIZED);
        }
        //存入ThreadLocal
        ThreadLocalUtil.set("customerId",JwtUtils.parseJWT(token).get("customerId"));
        log.info("用户id:{}", JwtUtils.parseJWT(token).get("customerId"));
        return true;
    }
}